<script setup lang="ts">
import type { FormState as PrinterForm } from './printer-connection.vue'
import {computed, onMounted, reactive, ref} from "vue";
import type { TableColumnType } from "ant-design-vue";
import { getWayBillNumber } from '@/api/waybill';
import { handleApi } from '@/utils/alert';
import { usePrinterStore } from '@/stores/printer';
import { useSwitchable } from '@/utils/hooks';

export type PrinterTaskProps = {
  // 打印机
  printer?: PrinterForm;
  // 打印的订单
  orders?: IOrder[];
}

export type PrinterTaskEmits = {
  close: [];
}

// 打印状态代码 0: waiting, 1: print, 2: complete, 3: failure, 4: cancel
export type PrintStatus = 0 | 1 | 2 | 3 | 4;

export type TaskItem = IWayBillOrder & {
  // 打印状态代码
  printStatus?: PrintStatus;
  printStatusStyle?: {
    color: string;
    text: string;
  };
  isError?: boolean;
  errMsg?: string;
  _task: any;
  _taskId?: string;
}

const { state, on, off } = useSwitchable()
const { state: complete } = useSwitchable(true)

const { printTask, waitTask } = usePrinterStore()

const props = defineProps<PrinterTaskProps>()
const emits = defineEmits<PrinterTaskEmits>()
const printTasks = reactive<TaskItem[]>([])
const ws = ref(null);
const connectWebSocket = (data: any) => {
  // 假设WebSocket服务器地址是 'ws://localhost:8080'
  ws.value = new WebSocket('ws://localhost:16888/ks/printer');

  ws.value.onopen = function (event) {
    console.log('WebSocket 连接已打开', event);
    ws.value.send(JSON.stringify(data))
  };
  ws.value.onerror = function (error) {
    console.error('WebSocket 出错', error);
  };
  ws.value.onmessage = function (event) {
    let returnData = JSON.parse(event.data)
    printTasks.map(item=>{
      if(item.taskId === returnData['taskID']){
        if(returnData.status === 'success'){
          item.print_status = 2
          item.printStatus = 2
          item.printStatusStyle = getStatus(2)
        }else{
          item.print_status = 3
          item.printStatus = 3
          item.printStatusStyle = getStatus(3)
        }
      }
    })
  };

  ws.value.onclose = function () {
    console.log('WebSocket 连接已关闭');
  };
}

onMounted(async () => {
  const res = await getWayBillNumber({ order_id: props.orders?.map(i => i.order_id)!, template_id: props.printer?.template! }).catch(handleApi)
  if (res) {
    res.data.print_params.map(item=>{
      item.printData.task.printer = props.printer.printer
      item.taskId = item.printData?.task?.taskID
      item.print_status = 1
      item.printStatus = 1
      item.printStatusStyle = getStatus(1)
      printTasks.push(item)
      connectWebSocket(item.printData)
    })
    // printTasks = res.data.print_params
    // console.log(res.data.print_params,'res')

    // connectWebSocket(res.data.print_params[0].printData)
    // connectWebSocket(configData)
    // res.data.print_params[0].printData
    // res.data.order_data.forEach((i, n) => {
    //   const printData: IWayBillPrintData | undefined = JSON.parse(i.tracking_print_data)
    //   const taskId = genTaskId(n)
    //   const contents: any[] = [{
    //     params: res.data.print_params,
    //     signature: printData?.sign,
    //     encryptedData: printData?.print_data,
    //     templateURL: res.data.template.standard_template_url
    //   }]
    //   if (res.data.template.url) {
    //     contents.push({
    //       data: i.print_data,
    //       templateURL: res.data.template.url
    //     })
    //   }
    //   printTasks.push({
    //     ...i,
    //     printStatusStyle: getStatus(0),
    //     printStatus: 0,
    //     isError: !printData || i.err_code !== 0,
    //     errMsg: i.err_msg || 'unknown error',
    //     _taskId: taskId,
    //     _task: {
    //       taskID: taskId,
    //       printer: props.printer?.printer,
    //       preview: false,
    //       documents: [{
    //         docNo: i.order_id,
    //         copy: 1,
    //         contents
    //       }]
    //     }
    //   });
    // })

    // await printAll()
  }
})

const printAll = async (skipSuccess = true) => {
  on()
  complete.value = false
  for (let i = 0; i < printTasks.length; i++) {
    if (skipSuccess && printTasks[i].printStatus === 2) continue
    if (!state) {
      printTasks[i].printStatus = 4
      printTasks[i].printStatusStyle = getStatus(4)
      continue
    }
    if (printTasks[i].isError) {
      printTasks[i].printStatus = 3
      printTasks[i].printStatusStyle = getStatus(3)
      continue
    }
    printTasks[i].printStatus = 1
    printTasks[i].printStatusStyle = getStatus(1)
    try {
      let pRes = await printTask(printTasks[i]._task)
      await waitTask(pRes.requestID, pRes.taskID)
      printTasks[i].printStatus = 2
      printTasks[i].printStatusStyle = getStatus(2)
    } catch {
      printTasks[i].printStatus = 3
      printTasks[i].printStatusStyle = getStatus(3)
    }
  }
  complete.value = true
  off()
}

const getStatus = (status: PrintStatus) => {
  let color = 'blue'
  let text = '打印等待'
  switch (status) {
    case 1:
      color = 'orange'
      text = '打印中'
      break
    case 2:
      color = 'green'
      text = '打印完成'
      break
    case 3:
      color = 'red'
      text = '打印失败'
      break
    case 4:
      color = '#ccc'
      text = '打印取消'
      break
  }
  return { color, text }
}

const genTaskId = (n: number) => new Date().getTime().toString(16) + 'N' + n.toString(16).padStart(3, '0')

const columns: (TableColumnType & DataIndex<TaskItem>)[] = [
  { key: 'parent_order_id', dataIndex: 'parent_order_id', title: '订单号' },
  // { key: 'taskId', dataIndex: '_taskId', title: '任务ID' },
  { key: 'taskID', dataIndex: 'taskID', title: '任务ID' },


  { key: 'print_status', title: '打印状态' },
  { key: 'tracking_number', dataIndex: 'tracking_number', title: '快递单号' }
]

const asTaskItem = (row: any) => row as TaskItem

const printedCount = computed(() => printTasks.filter(i => i.printStatus === 2).length)
const failedCount = computed(() => printTasks.filter(i => i.printStatus === 3).length)

const printSuccess = computed(() => printTasks.filter(i => i.printStatus === 2).length === printTasks.length && printTasks.length !== 0)
const rePrint = () => {
  printTasks.forEach(i => {
    i.printStatus = 0
    i.printStatusStyle = getStatus(0)
  })
  printAll()
}


</script>

<template>
  <div class="py-2">需要打印 {{ props.orders?.length }} 个订单, 已成功打印 {{ printedCount }} 个订单, 打印失败 {{ failedCount }} 个</div>
  <ATable
    size="small"
    :data-source="printTasks"
    :columns="columns"
    :pagination="false"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'taskID'">
        <div>{{ record.taskId || record.task?.taskID }}</div>
      </template>
      <template v-if="column.key === 'print_status'">
        <ATag :color="asTaskItem(record).printStatusStyle?.color">{{ asTaskItem(record).printStatusStyle?.text }}</ATag>
        <div class="w-[200px]" v-if="(record as TaskItem).isError">{{ (record as TaskItem).errMsg }}</div>
      </template>

    </template>
  </ATable>
  <div class="flex space-x-2 justify-end py-2">
    <AButton danger v-if="state" @click="off" :disabled="!complete">中止打印</AButton>
    <AButton type="primary" v-else-if="!printSuccess" @click="printAll(true)" :disabled="!complete">继续打印</AButton>
    <AButton type="primary" v-else-if="printSuccess" @click="rePrint" :disabled="!complete">重新打印</AButton>
    <AButton danger @click="emits('close')" :disabled="!complete">关闭</AButton>
  </div>
</template>